package com.gexiaobao.pigeon.ui.fragment.setting

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentReceiveAddressBinding
import com.gexiaobao.pigeon.ui.adapter.ReceiveAddressAdapter
import com.gexiaobao.pigeon.viewmodel.SettingViewModel
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 18:39
 * @Describe    : 收货地址
 */
class FragmentReceiveAddress : BaseFragment<SettingViewModel, FragmentReceiveAddressBinding>() {

    private val mAdapter: ReceiveAddressAdapter by lazy { ReceiveAddressAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>
    private var mType = 0

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.tvWhiteTitle.text = "收货地址"
        mDatabind.includeBar.tvRedBarRightMenu.text = "添加地址"
        mDatabind.includeBar.tvRedBarRightMenu.visibility = View.VISIBLE

        mType = requireArguments().getInt("type")
        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(activity)
                .setBackground(R.color.delete_bg)
                .setTextColor(Color.WHITE)
                .setText(R.string.delete)
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.layoutList.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 左侧还是右侧菜单 */
//            val direction = menuBridge.direction
//            /**  菜单在Item中的Position */
//            val menuPosition = menuBridge.position
            /** 调用删除接口 */
            showLoading(getString(R.string.loading))
            mViewModel.delShippingAddress(mAdapter.data[position].id.toString())
        }
        mDatabind.layoutList.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        mViewModel.getAddressList()
    }

    override fun initData() {
        super.initData()
        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getAddressList()
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getAddressList()
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 0f))
        )

        mAdapter.setEditBtnHide(mType == 1)
        setFragmentResultListener("editSuccess") { _, bundle ->
            if (bundle.getBoolean("isSuccess")) {
                loadsir.showLoading()
                mViewModel.getAddressList()
            }
        }

        if (mType == 1) {
            mAdapter.setOnItemClickListener { _, _, position ->
                CacheUtil.setAddressInfo(mAdapter.data[position])
                eventViewModel.toNotifyChangeAddress.value = mAdapter.data[position].id//通知修改了地址
//                setFragmentResult("address", Bundle().apply {
//                    putParcelable(Constant.DATA_BEAN, mAdapter.data[position])
//                })
                nav().navigateUp()
            }
        }

        mAdapter.addChildClickViewIds(R.id.ivAddressEdit)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            nav().navigateAction(R.id.action_to_add_receive_address, Bundle().apply {
                putParcelable(Constant.DATA_BEAN, mAdapter.data[position])
                putString("type", "modify")
            })
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 删除收货地址 */
        mViewModel.delAddressResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                lazyLoadData()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取用户设置地址  */
        mViewModel.addressResult.observe(viewLifecycleOwner) {
            if (it.isEmpty) {
                CacheUtil.setAddressInfo(null)
            }
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.includeBar.tvRedBarRightMenu) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.includeBar.tvRedBarRightMenu -> {
                    nav().navigateAction(R.id.action_to_add_receive_address, Bundle().apply {
                        putString("type", "")
                    })
                }
            }
        }
    }
}